package com.icode.async;

import java.util.concurrent.*;

/**
 * @Author: my_code
 * @Email: my_code@foxmail.com
 * @Create: 2020-12-14 13:55
 * <p>
 * 异步编排 CompletableFuture
 */
public class Test2 {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("main--start");
        ExecutorService executor = new ThreadPoolExecutor(5, 10, 10L, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(50),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());

        CompletableFuture<Integer> future1 = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync--start");
            int i = 256 << 1;
            System.out.println(i + "    无参数，有返回值");
            System.out.println("supplyAsync--end");
            return i;
        }, executor).thenApplyAsync(i -> {
            System.out.println("thenApplyAsync--start");
            System.out.println((i <<= 1) + "    有参数，有返回值");
            System.out.println("thenApplyAsync--end");
            return i;
        }, executor);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {
            System.out.println("supplyAsync--start");
            String str = "hello";
            System.out.println(str + "    无参数，有返回值");
            System.out.println("supplyAsync--end");
            return str;
        }, executor).thenCombineAsync(future1, (str, integer) -> {
            System.out.println("thenCombine--start");
            str = str + " " + integer;
            System.out.println(str + "    有两个参数，并有一个返回值");
            System.out.println("thenCombine--end");
            return str;
        }, executor);
        future2.get();
        executor.shutdown();
        System.out.println("main--end");
    }
}
